<template>
  <div>
    <!-- 1.0面包屑 -->
    <my-breadcrumb level1="商品管理" level2="商品分类"></my-breadcrumb>
    <!-- 2.0.级联菜单 若需要允许用户选择任意一级选项，则可将change-on-select赋值为true
    v-model="selectedOptions"设置默认值-->
    <el-cascader
      :options="options"
      v-model="selectedOptions"
      :show-all-levels="false"
      change-on-select
      :props="props"
      @change="categoryChange"
    ></el-cascader>
    <!-- 3.0tab切换栏 -->
    <el-tabs type="border-card" @tab-click="tabClick" v-model="type">
      <el-tab-pane label="动态参数" name="dynamic">
        <el-button type="success" plain @click="adddynamicParams=true">添加动态参数</el-button>
        <el-table :data="dynamicParams" style="width: 100%" border>
          <el-table-column type="expand">
            <template slot-scope="scoped">
              <el-tag
                :key="index"
                v-for="(tag,index) in scoped.row.attr_vals"
                closable
                :disable-transitions="false"
                @close="deleteAttrVal(index,scoped.row)"
              >{{tag}}</el-tag>
              <el-input
                class="input-new-tag"
                placeholder="按回车添加属性值"
                v-if="scoped.row.inputVisible"
                v-model="scoped.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="addDynamicParamsValue(scoped.row)"
                @blur="hideInput(scoped.row)"
              ></el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(scoped.row)"
              >+ 添加值</el-button>
            </template>
          </el-table-column>
          <el-table-column label="#" type="index"></el-table-column>
          <el-table-column prop="attr_name" label="分类参数名称" width="500"></el-table-column>
          <el-table-column label="操作" width="500">
            <template slot-scope="scope">
              <el-button
                icon="el-icon-edit"
                type="primary"
                size="mini"
                plain
                @click="editDynamicParams(scope.row)"
              ></el-button>
              <el-button
                size="mini"
                icon="el-icon-delete"
                type="danger"
                @click="deleteRoles(scope.row.id)"
                plain
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="静态参数" name="static">
        <el-button type="success" plain>添加静态参数</el-button>
        <el-table :data="staticParams" style="width: 100%" border>
          <el-table-column label="#" type="index"></el-table-column>
          <el-table-column prop="attr_name" label="属性名称" width="200"></el-table-column>
          <el-table-column prop="attr_name" label="属性值" width="400"></el-table-column>
          <el-table-column label="操作" width="500">
            <template slot-scope="scope">
              <el-button
                icon="el-icon-edit"
                type="primary"
                size="mini"
                plain
                @click="editDynamicParams(scope.row)"
              ></el-button>
              <el-button
                size="mini"
                icon="el-icon-delete"
                type="danger"
                @click="deleteDynamicParams(scope.row.id)"
                plain
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <!-- 4.0添加动态属性对话框 -->
    <el-dialog title="添加动态参数" :visible.sync="dialogVisible4AddDynamicParams" width="50%">
      <el-form :model="addDynamicParamsObj" :rules="rules" ref="addParamsForm" label-width="100px">
        <el-form-item label="参数名称" prop="attr_name">
          <el-input v-model="addDynamicParamsObj.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible4AddDynamicParams = false">取 消</el-button>
        <el-button type="primary" @click="submitAddDynamicParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 5.0修改动态参数属性对话框 -->
    <el-dialog title="修改动态参数" :visible.sync="dialogVisible4EditDynamicParams" width="50%">
      <el-form
        :model="editDynamicParamsObj"
        :rules="rules"
        ref="editDynamicParamsForm"
        label-width="100px"
      >
        <el-form-item label="参数名称" prop="attr_name">
          <el-input v-model="editDynamicParamsObj.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible4EditDynamicParams = false">取 消</el-button>
        <el-button type="primary" @click="submitEditDynamicParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
//导入面包屑组件
import MyBreadcrumb from '../subcomponents/MyBreadcrumb'
export default {
  //注册子组件
  components: {
    'my-breadcrumb': MyBreadcrumb
  },
  data() {
    return {
      options: [], //级联菜单数据
      selectedOptions: [], //默认选中的数据
      paramsList: [], //参数表格的数据
      props: {
        label: 'cat_name',
        children: 'children',
        value: 'cat_id'
      },
      type: 'dynamic', //绑定tab切换的默认值属性
      thirdLevelId: 0, //三级分类id
      attr_id: 0, //包括动态参数和静态参数id
      dynamicParams: [], //动态参数属性
      staticParams: [], //静态参数属性
      attr_vals: '',
      dialogVisible4AddDynamicParams: false,
      dialogVisible4EditDynamicParams: false,
      addDynamicParamsObj: {
        attr_name: '',
        attr_sel: 'many'
        
      }, //添加动态参数的数据
      editDynamicParamsObj: {
        attr_name: '',
        attr_sel: 'many'
      }, //修改动态参数
      rules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ],
        attr_vals: [
          { required: true, message: '请输入参数值', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCategoriesDate()
  },
  methods: {
    getCategoriesDate() {
      this.$axios
        .get(`categories`, {
          params: {
            type: 3
          }
        })
        .then(res => {
          //   console.log(res)
          //赋值给模型
          this.options = res.data.data

          //如果不想默认值写死就把一级的id 二级id 三级id 传给selectedOptions
          const firstId = res.data.data[0].cat_id
          const secondId = res.data.data[0].children[0].cat_id
          const thirdId = res.data.data[0].children[0].children[0].cat_id
          //重新赋值给默认选中框
          this.selectedOptions = [firstId, secondId, thirdId]
          //三级id赋值
          this.thirdLevelId = thirdId
          //判断加载的是动态还是静态
          if (this.type === 'dynamic') {
            console.log(this)
            this.getThreeDynamicParams()
          } else {
            this.getThreeStaticParams()
          }
        })
    },
    //当我们的级联菜单发生了变化
    categoryChange(val) {
      //判断是否选中的是三级
      if (val.length < 3) {
        this.$message('必须要输入三级选项哦')
        return
      }
      this.thirdLevelId = val[2]
      if (this.type === 'dynamic') {
        this.getThreeDynamicParams()
      } else if (this.type === 'static') {
        this.getThreeStaticParams()
      }
    },
    //tab切换事件
    tabClick(val) {
      //当点击tab切换时触发,显示对应的内容
      this.type = val.name
      //获取三级动态参数后还要判断是动态还是静态
      if (this.type === 'dynamic') {
        this.getThreeDynamicParams()
      } else if (this.type === 'static') {
        this.getThreeStaticParams()
      }
    },
    //获取三级动态参数
    getThreeDynamicParams() {
      // console.log('1111',this.thirdLevelId)
      this.$axios
        .get(`categories/${this.thirdLevelId}/attributes`, {
          params: {
            sel: 'many'
          }
        })
        .then(res => {
          console.log(res)

          res.data.data.forEach(item => {
            if (item.attr_vals.trim().length === 0) {
              item.attr_vals = []
            } else {
              item.attr_vals = item.attr_vals.split(',')
            }
            //在后台返回的基础上再加上两个属性
            item.inputVisible = false
            item.inputValue = ''
          })
          this.dynamicParams = res.data.data
        })
    },
    //获取三级静态参数
    getThreeStaticParams() {
      // console.log('2222',this.thirdLevelId)
      this.$axios
        .get(`categories/${this.thirdLevelId}/attributes`, {
          params: {
            sel: 'only'
          }
        })
        .then(res => {
          this.staticParams = res.data.data
        })
    },
    //添加动态参数 并弹框
    submitAddDynamicParams() {
      this.$refs.addParamsForm.validate(valid => {
        if (valid) {
          this.$axios
            .post(
              `categories/${this.thirdLevelId}/attributes`,
              this.addDynamicParamsObj
            )
            .then(res => {
              if (res.data.meta.status === 201) {
                // 提示
                this.$message({
                  type: 'success',
                  message: res.data.meta.msg
                })
                // 隐藏对话框
                this.dialogVisible4AddDynamicParams = false
                // 重新查询列表
                this.getThreeDynamicParams()
              }
            })
        }
      })
    },
    //修改分类  并弹框
    editDynamicParams(obj) {
      this.attr_id = obj.attr_id
      this.editDynamicParamsObj.attr_name = obj.attr_name

      this.dialogVisible4EditDynamicParams = true
    },
    submitEditDynamicParams(attr_name, attr_id) {
      this.$refs.editDynamicParamsForm
        .validate(valid => {
          if (valid) {
            this.$axios.put(
              `categories/${this.thirdLevelId}/attributes/${this.attr_id}`,
              this.editDynamicParamsObj
            )
          }
        })
        .then(res => {
          console.log(res)
          if (res.data.meta.status !== 200) {
            //提示修改失败
            this.$message.error(res.data.meta.msg)
          } else {
            this.$message({
              message: '修改用户信息成功',
              type: 'success'
            })
            //关闭对话框
            this.dialogVisible4EditDynamicParams = false
            //刷新列表
            this.getThreeDynamicParams()
          }
        })
    },
    //删除某个动态属性的值
    deleteAttrVal(index, dparams) {
      // 删除dparams中的attr_vals
      dparams.attr_vals.splice(index, 1)

      // 调用接口去更新动态参数的值
      this.addOrRemoveParamsAttrValues(dparams)
    },
    //添加某个动态属性的值
    addDynamicParamsValue(dparams) {
      if (dparams.inputValue.trim().length === 0) {
        this.$message({
          message: '输入内容之后，才能添加哦',
          type: 'warning'
        })
        return
      }
      // 给当数组添加内容，就会导致视图发生变化
      this.attr_vals.push(dparams.inputValue)
      //添加动态的值
      this.addOrRemoveParamsAttrValues(dparams)
    },
    //添加或是删除动态参数的值
    addOrRemoveParamsAttrValues(dparams) {
      this.$axios
        .put(`categories/${this.thirdLevelId}/attributes/${dparams.attr_id}`, {
          attr_name: dparams.attr_name,
          attr_sel: 'many',
          attr_vals: dparams.attr_vals.join(',')
        })
        .then(res => {
          if (res.data.meta.status === 200) {
            // 弹出正确的提示
            this.$message({
              message: res.data.meta.msg,
              type: 'success'
            })

            // 清空我们的dparams的inputValue的值，让inputVisible设置为false
            dparams.inputValue = ''
            dparams.inputVisible = false
          }
        })
    },
    //失去焦点事件 让input框隐藏
    hideInput(dparams) {
      dparams.inputVisible = false
    },
    //当点击按钮 让input出来 并且获得焦点

    handleInputConfirm() {
      let inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    showInput(dparams) {
      //更改之后,vue会重新渲染
      console.log(dparams)
      dparams.inputVisible = true
      //等我们的页面完全渲染后才能拿到dom操作
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  }
}
</script>
<style scoped>
/* 添加分类参数页面的添加值样式 */
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 150px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>

